﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class ABUpdateManager : MonoBehaviour
{
    string StreamingPath;//Streaming路径
    string DataPath;//沙盒路径
    string BaseUrl = "http://192.168.108.11/StreamingAssets/";

    public static event System.Action Complete;

    void Awake()
    {
        StreamingPath = Application.streamingAssetsPath + "/";

        //ios和android唯一一个可读可写的文件夹
        DataPath = Application.persistentDataPath + "/";

        Debug.Log("检测本地沙盒目录" + DataPath);
        if (File.Exists(DataPath + "file.txt"))
        {
            Debug.Log("沙盒目录不为空");

            //本地沙盒内已有文件，检测更新
            StartCoroutine(CheckUpdate());
        }
        else
        {
            //本地沙盒没有文件，拷贝StreamingAsset到PersitentDatapath
            //首次运行程序
            Debug.Log("沙盒目录为空");
            CheckCompress();
        }
    }

    IEnumerator CheckUpdate()
    {
        Debug.Log("获取远程file.txt文件");
        string fileUrl = BaseUrl + "file.txt";
        WWW www = new WWW(fileUrl);
        yield return www;
        if (www.error != null)
        {
            Debug.Log(www.error);
            yield return 0;
        }
        string[] remotefiles = www.text.Split('\n');
        Dictionary<string, string> remoteDic = new Dictionary<string, string>();
        foreach (var line in remotefiles)
        {
            Debug.Log("line:" + line);
            string[] keys = line.Split('|');
            remoteDic.Add(keys[0], keys[1]);
        }

        //获取本地file
        string filePath = DataPath + "file.txt";
        string[] localfiles = File.ReadAllText(filePath).Split('\n');
        Dictionary<string, string> localDic = new Dictionary<string, string>();
        foreach (var item in localfiles)
        {
            string[] keys = item.Split('|');
            localDic.Add(keys[0], keys[1]);
        }

        //比较差异
        foreach (var item in remoteDic)
        {
            string fileName = item.Key;
            Debug.Log("检测更新" + fileName);

            if (localDic.ContainsKey(item.Key))
            {
                //本地和远程都有此文件，比对MD5
                string remoteMD5 = remoteDic[fileName];
                string localMD5 = localDic[fileName];

                //MD5不同，更新文件
                if (remoteMD5 != localMD5)
                {
                    Debug.Log("MD5不同，更新：" + fileName);

                    File.Delete(DataPath + fileName);//删除沙盒旧文件
                    StartCoroutine(DownloadFile(fileName));
                }
            }
            else
            {
                //本地缺少文件，直接下载
                Debug.Log("本地缺少文件，直接下载：" + fileName);
                StartCoroutine(DownloadFile(fileName));
            }
        }

        //更新file
        File.Delete(DataPath + "file.txt");//删除沙盒旧file
        File.WriteAllText(DataPath + "file.txt", www.text);//写入新file

        Debug.Log("解压更新完成");
        if (Complete!=null)
        {
            Complete();
        }
    }

    IEnumerator DownloadFile(string fileName)
    {
        WWW download = new WWW(BaseUrl + fileName);
        yield return download;

        File.WriteAllBytes(DataPath + fileName, download.bytes);
        Debug.LogFormat("更新文件{0}成功", fileName);
    }

    void CheckCompress()
    {
        string[] files = Directory.GetFiles(StreamingPath);

        foreach (var sourcepath in files)
        {
            string targetpath = DataPath + Path.GetFileName(sourcepath);
            Debug.Log("Copy file:" + sourcepath + "==>" + targetpath);

            //targetpath已经存在，拷贝失败 ，ioException
            if (File.Exists(targetpath))
            {
                File.Delete(targetpath);
            }

            File.Copy(sourcepath, targetpath);
        }

        //解压完成，检测更新
        StartCoroutine(CheckUpdate());
    }
}
